﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
//using System.Web.Mail;
using System.Net.Mail;
using System.Data;
using System.Data.SqlClient;
using System.Security.Cryptography;
using System.Text;
using System.Net;


public partial class QuenMatKhau : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btGoiEmail_Click(object sender, EventArgs e)
    {
        //System.Web.Mail.MailMessage objEmail = new System.Web.Mail.MailMessage();
        
        DataTable dtb = LayTenDangNhap(txtEmail.Text);
        if (dtb.Rows.Count > 0)
        {
            System.Net.Mail.MailMessage ms = new System.Net.Mail.MailMessage();
            ms.To.Add(txtEmail.Text);
            ms.From = new MailAddress("casperremix@gmail.com", "Cas per", System.Text.Encoding.UTF8);
            ms.Subject = "Thông tin về mật khẩu của bạn";
            ms.Body = NoiDungMail();
            ms.BodyEncoding = Encoding.UTF8;

            ms.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;

            ms.IsBodyHtml = true;
            try
            {           
               


                SmtpClient client = new SmtpClient();
                client.Host = "smtp.gmail.com";
                client.EnableSsl = true;
                client.Port = 587;


                client.Credentials = new NetworkCredential("casperremix@gmail.com","tranthanhbach");

                client.Send(ms);
                //SmtpMail.Send(objEmail);
                ScriptManager.RegisterStartupScript(this, this.GetType(), "redirectMe", "at('Chúng tôi đã gửi mật khẩu cho bạn.\\n\\n Vui lòng check mail để lấy lại mật khẩu!');location.href='LoginInfo.aspx';", true);
            }
            catch (Exception exc)
            {
                Response.Write("Send failure: " + exc.ToString());
            }
        }
        else
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "redirectMe", "alert('Email của bạn chưa đăng ký!');", true);
        }
    }

    private string NoiDungMail()
    {
        string NoiDung = "";
        DataTable dtb = LayTenDangNhap(txtEmail.Text);
        string MatKhauMoi = "", TenDangNhap = "";
        if (dtb.Rows.Count > 0)
        {
            NoiDung = "Đây là Mail gửi đến từ website của Yourwebsite..<br>";
            MatKhauMoi = MaNgauNhien_SoChu(7);
            NoiDung += "Mật khẩu mới của bạn là: " + MatKhauMoi;
            TenDangNhap = dtb.Rows[0]["tai_khoan"].ToString().Trim();
            DoiMatKhau(TenDangNhap, MatKhauMoi);
            NoiDung += "<br>Sau khi đăng nhập bạn nˆn đổi lại mật khẩu để tiện cho việc đăng nhập lần tiếp theo";
            NoiDung += "<br><br><hr>Vui lòng không trả lời Mail này!";
        }
        return NoiDung;
    }

    //private void CapNhatMatKhau(string TenDangNhap, string MatKhau)
    //{
    //    //tinh sau
    //    string connectString = @"Server =.\SQL2005;Initial Catalog=DataBaseNamr;User ID=sa;Password=******";
    //    string queryUpdate = @"UPDATE TB_ThanhVien SET MatKhau=" + MatKhau + "	 WHERE TenDangNhap=" + TenDangNhap;
    //    SqlConnection conn = new SqlConnection(connectString);
    //    try
    //    {
    //        conn.Open();
    //        // Thực thi cƒu lệnh Update
    //        SqlCommand cmdInsert = new SqlCommand(queryUpdate, conn);
    //        cmdInsert.ExecuteNonQuery();
    //    }
    //    catch (SqlException ex)
    //    {
    //        Console.WriteLine("Error: " + ex);
    //    }
    //    finally
    //    {
    //        conn.Close();
    //    }
    //}


    public int Kiemtra(string id, string pass)
    {

        pass = MaHoaMatKhau(pass);
        ConnectionData conn = new ConnectionData();
        string sql = "select * from khach_hang where tai_khoan = '" + id + "' and mat_khau = '" + pass + "'";


        if (conn.LayDangNhap(sql) == 1)
            return 1;
        else
            return 0;
    }

    public void DoiMatKhau(string TaiKhoan, string MatKhauMoi)
    {
        MatKhauMoi = MaHoaMatKhau(MatKhauMoi);
        String sql = "Update khach_hang set mat_khau = '" + MatKhauMoi + "' where tai_khoan = '" + TaiKhoan + "'";
        ConnectionData cn = new ConnectionData();
        if (cn.ExecuteSQL(sql) == 1)
        {
            //Response.Redirect("ThayDoiMatKhauThanhCong.aspx");
        }
    }

    private DataTable LayTenDangNhap(string Email)
    {
        
        //tinh sau
        DataTable dtbTmp = new DataTable();
        //string connString = @"Server =.\SQL2005;Initial Catalog=DataBaseNamr;User ID=sa;Password=******";
        string sql = @"SELECT tai_khoan FROM khach_hang WHERE Email= '" + Email +"'";
        ConnectionData cn = new ConnectionData();
        try
        {
            // Mở kết nối

            DataSet ds = cn.ExecuteQuery(sql);
            
            dtbTmp = ds.Tables[0];
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
        return dtbTmp;
    }

    public string MaNgauNhien_So(int codeCount)
    {
        string allChar = "0,1,2,3,4,5,6,7,8,9";
        string[] allCharArray = allChar.Split(',');
        string randomCode = "";
        int temp = -1;

        Random rand = new Random();
        for (int i = 0; i < codeCount; i++)
        {
            if (temp != -1)
            {
                rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
            }
            int t = rand.Next(10);
            if (temp != -1 && temp == t)
            {
                return MaNgauNhien_So(codeCount);
            }
            temp = t;
            randomCode += allCharArray[t];
        }
        return randomCode;
    }

    public string MaNgauNhien_SoChu(int codeCount)
    {
        string allChar = "0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z";
        string[] allCharArray = allChar.Split(',');
        string randomCode = "";
        int temp = -1;

        Random rand = new Random();
        for (int i = 0; i < codeCount; i++)
        {
            if (temp != -1)
            {
                rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
            }
            int t = rand.Next(36);
            if (temp != -1 && temp == t)
            {
                return MaNgauNhien_SoChu(codeCount);
            }
            temp = t;
            randomCode += allCharArray[t];
        }
        return randomCode;
    }

    public string CreateLostPassword(int PasswordLength)
    {
        string _allowedChars = "abcdefghijk0123456789mnopqrstuvwxyz";
        Random randNum = new Random();
        char[] chars = new char[PasswordLength];
        int allowedCharCount = _allowedChars.Length;

        for (int i = 0; i < PasswordLength; i++)
        {
            chars[i] = _allowedChars[(int)((_allowedChars.Length) * randNum.NextDouble())];
        }
        return new string(chars);
    }

    public string MaHoaMatKhau(string password)
    {
        UnicodeEncoding encoding = new UnicodeEncoding();
        Byte[] hashBytes = encoding.GetBytes(password);
        // Compute the SHA-1 hash
        SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
        Byte[] cryptPassword = sha1.ComputeHash(hashBytes);
        return BitConverter.ToString(cryptPassword);
    }
}